package com.question.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.question.Exception.BaseException;
import com.question.Vo.SessionWebUserDto;
import com.question.entity.User;
import com.question.mapper.UserMapper;
import com.question.service.UserService;
import jakarta.annotation.Resource;
import jodd.bean.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    public SessionWebUserDto login(String username, String password, Integer roles) {
        SessionWebUserDto sessionWebUserDto = new SessionWebUserDto();
        if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password) || ObjectUtils.isEmpty(roles)) {
            throw new BaseException("请输入必填项");
        }
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        lambdaQueryWrapper.eq(User::getPassword, password);
        lambdaQueryWrapper.eq(User::getRoles, roles);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (user == null) {
            throw new BaseException("用户不存在");
        }
        BeanUtils.copyProperties(user,sessionWebUserDto);
        sessionWebUserDto.setId(Math.toIntExact(user.getId()));
        return sessionWebUserDto;


    }
    public   void register(String username, String password){
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        lambdaQueryWrapper.eq(User::getRoles,1);
       Long count=userMapper.selectCount(lambdaQueryWrapper);
       if(count>0){
           throw new BaseException("该账号已存在");
       }
       User user=new User();
       user.setCreatetime(new Date());
       user.setUsername(username);
       user.setPassword(password);
       user.setRoles(1);
       userMapper.insert(user);


    }
}
